// pages/shopinfo/shopinfo.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods_id:'',
    choosesize:[],
    chooseSizeName:[],
    shopSize:[],
    buyNumber:1,
    timer:null,
    safeAreaB:0,
    firstLoadding:false,
    loadding:false,
    shopExist:true
  },
  closeState:function(){
    this.setData({
      sizeState:false,//规格显示
      couponState:false//优惠券显示
    })
  },
  openCoupon:function(){
    if(this.data.couponlist.length==0)return;
    this.setData({
      couponState:true
    })
  },
  openshopSize:function(){
    this.setData({
      sizeState:true
    })
  },
  computeNumber:function(e){
    let type=e.currentTarget.dataset.type;
    let number=Number(this.data.buyNumber);
    if(type==1)number=number==1?1:number-1;
    else number=number+1;
    this.setData({
      buyNumber:number
    })
  },
  submitBuy:function(e){
    if(app.globalData.token==''){
      app.userlogin();
      return
    }
    if(this.data.loadding)return;
    let type=e.currentTarget.dataset.type;
    let goods_id=this.data.goods_id;
    let goods_num=this.data.buyNumber;
    let item_id=this.data.shopSizes.item_id || '';
    let shopSize=this.data.shopSize;
    if(item_id=='' && shopSize.length>0){
      app.utilJs.toast({ title:"请选择商品规格"});
      return
    }
    this.setData({
      loadding:true
    })
    let data={token:app.globalData.token,goods_id,goods_num,item_id};
    if(type==1)this.addCartApi(data);
    else this.nowBuyApi(data);
  },
  addCartApi:function(data){//加入购物车
    app.requestJs('Cart/addcart',{data}).then((res)=>{
      // console.log(res)
      // return false
      if(res.errcode==1){
        this.getshopInfo();
        setTimeout(() => {
          app.utilJs.toast({ title: res.message });
        },200);
      }else {
        this.setData({loadding:false});
        app.utilJs.toast({ title: res.message });
      }
    })
  },
  nowBuyApi:function(data){
    wx.navigateTo({
      url: '/pages/order/created_order/created_order?goods_id='+data.goods_id+'&goods_num='+data.goods_num+'&item_id='+data.item_id+'&action=buynow',
      events:{

      }
    })
  },
  getshopInfo:function(id){
    let goods_id=id || this.data.goods_id;
    let data={goods_id,token:app.globalData.token};
    app.requestJs('goods/goods_detail',{data}).then((res)=>{
      if(res.errcode==1){
        let resData=res.data || {};
        let shopSizes={};
        if(resData.is_prom)shopSizes={item_id:'',price:resData.prom_good.price,market_price:resData.market_price,
        store_count:resData.store_count,goods_name:resData.goods_name};//活动价
        else shopSizes={
          item_id:'',
          price:resData.price,
          market_price:resData.market_price,
          store_count:resData.store_count,
          goods_name:resData.goods_name
        };//正常价
        let shopDetail=app.utilJs.richText(resData.goods_content || '');
        this.setData({
          shopInfo:resData,
          banner:resData.goods_images || [],
          prom_good:resData.prom_good,
          shopSizes,
          shopDetail,
          firstLoadding:true,
          goods_id,
          loadding:false,
          shopExist:true
        })
        this.getShopsize(data.goods_id);
        if(resData.is_prom)this.setIntervalApi(resData.prom_good.surplustime);
      }else {
        this.setData({
          shopExist:false
        })
        app.utilJs.toast({ title: res.message });
      }
    })
  },
  getShopsize:function(goods_id){
    let data={goods_id}
    app.requestJs('goods/getgoodsitem',{data}).then((res)=>{
      if(res.errcode==1){
        let resData=res.data || [];
        let choosesize=resData.map(item=>'');
        let chooseSizeName=resData.length==0?[this.data.shopSize.goods_name]:[];
        this.setData({
          shopSize:resData,
          choosesize,
          chooseSizeName
        })
      }else app.utilJs.toast({ title: res.message });
    })
  },
  getcoupon:function(couponP){
    let data={p:couponP,token:app.globalData.token};
    app.requestJs('goods/couponlist',{data}).then((res)=>{
      if(res.errcode==1){
        let resData=res.data || [];
        this.setData({
          couponlist:data.p==1?resData:[...this.data.couponlist,...resData],
          couponP:data.p,
          couponPageLodding:resData.length>=10?false:true
        })
      }else app.utilJs.toast({ title: res.message });
    })
  },
  bindPage:function(){
    console.log("优惠券分页");
    if(this.data.couponPageLodding)return;
    let p=this.data.couponP+1;
    this.getcoupon(p);
  },
  userGetcoupon:function(e){
    let coupon_id=e.currentTarget.dataset.id;
    let data={coupon_id,token:app.globalData.token};
    app.requestJs('goods/getcoupon',{data}).then((res)=>{
      if(res.errcode==1){
        this.getcoupon(1);
        setTimeout(() => {
          app.utilJs.toast({ title: res.message });
        },200);
      }else app.utilJs.toast({ title: res.message });
    })
  },
  chooseSize:function(e){
    console.log(e);
    let index=e.currentTarget.dataset.index;
    let choosesize=this.data.choosesize;
    let chooseSizeName=this.data.chooseSizeName;
    let item_id=e.currentTarget.dataset.id;
    let name=e.currentTarget.dataset.name;
    choosesize[index]=item_id;
    chooseSizeName[index]=name;
    let checkedIndex=choosesize.findIndex(item=>item=='');
    if(checkedIndex==-1)this.getsizeInfo(choosesize);
    this.setData({choosesize,chooseSizeName});
  },
  getsizeInfo:function(item_id){
    let goods_id=this.data.goods_id;
    let data={goods_id,item_id:item_id.join("_")};
    app.requestJs('goods/getspecgoods',{data}).then((res)=>{
      if(res.errcode==1){
        let resData=res.data || {};
        this.setData({
          // choosesize:item_id,
          shopSizes:resData
        })
      }else app.utilJs.toast({ title: res.message });
    })
  },
  collectShop:function(){
    let goods_id=this.data.goods_id;
    let data={goods_id,token:app.globalData.token};
    app.requestJs('goods/collect_goods',{data}).then((res)=>{
      if(res.errcode==1){
        this.getshopInfo();
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('updateData', {data: 'test'});
      }else app.utilJs.toast({ title: res.message });
    })
  },
  setIntervalApi:function(time){//计时器
    if(time==0){
      clearInterval(this.data.timer);
      return
    }
    let timer=this.data.timer;
    let outTime='';
    timer=setInterval(()=>{
      console.log(this.data.timer);
      if(time==0){
        clearInterval(this.data.timer);
        this.getIndex();
      }else if(!this.data.timer)clearInterval(this.data.timer);
      else time=time-1;
      let hTime=time;
      console.log(time);
      // let d=Math.floor(time/86400)>9?Math.floor(time/86400):'0'+Math.floor(time/86400);
      // let hTime=time%86400;
      let h=Math.floor(hTime/3600)>9?Math.floor(hTime/3600):'0'+Math.floor(hTime/3600);
      let mTime=hTime%3600;
      let m=Math.floor(mTime/60)>9?Math.floor(mTime/60):'0'+Math.floor(mTime/60);
      let s=mTime%60>9?mTime%60:'0'+mTime%60;
      // outTime=h+':'+m+':'+s;
      outTime={h,m,s};
      // outTime=d=='00'?h+':'+m+':'+s:d+'天'+h+':'+m+':'+s;
      this.setData({
        outTime
      })
    },1000);
    this.setData({
      timer
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      safeAreaB:app.globalData.safeArea
    })
    let goods_id=options.shopid || '';
    this.getshopInfo(goods_id);
    this.getcoupon(1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let token = wx.getStorageSync("token") ? wx.getStorageSync("token"):'';
    app.globalData.token=token;
    if(this.data.firstLoadding){
      this.getshopInfo();
      this.getcoupon(1);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that=this;
    clearInterval(that.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that=this;
    clearInterval(that.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})